package org.glut.saltedfish.servlet;

import com.google.gson.GsonBuilder;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.glut.saltedfish.domain.ChatRecords;
import org.glut.saltedfish.service.ChatRecordsServiceImpl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet(value = "/chatRecords")
public class ChatRecordsServlet extends HttpServlet {

    /**
     * 处理客户端发起的 GET 请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        //设置响应的内容 MINE 类型
        resp.setContentType("application/json;charset=UTF-8");

        //获得请求参数，请求参数为字符串，需转化为整型
        Integer senderId = null;
        Integer receiverId = null;

        if (req.getParameter("senderId") != null) {
            senderId = Integer.valueOf(req.getParameter("senderId"));
        }
        if (req.getParameter("receiverId") != null) {
            receiverId = Integer.valueOf(req.getParameter("receiverId"));
        }

        List<ChatRecords> chat_recordsBySI = new ChatRecordsServiceImpl().viewMessageBySI(senderId, receiverId);
        List<ChatRecords> chat_recordsByRI = new ChatRecordsServiceImpl().viewMessageByRI(senderId, receiverId);

        List<ChatRecords> allChatRecords = new ArrayList<>();
        allChatRecords.addAll(chat_recordsBySI);
        allChatRecords.addAll(chat_recordsByRI);

        new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .setPrettyPrinting() //设置 json 格式，有缩进
                .create()
                .toJson(allChatRecords,writer);
    }

    /**
     * 处理客户端发起的 POST 请求
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
